package com.yy.ttmodule.udp;


import android.support.annotation.NonNull;
import android.util.Log;

import com.yy.ttmodule.utils.Logger;

import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpServer {

    private final String TAG = "UdpServer";

    private int mPort = 0;

    private DatagramSocket mSocket = null;
    private int mSocketBufferSize = 0;

    static boolean isSendData = false;
    static boolean isReadData = false;

    public UdpServer(int bufferSize, int port) {
        init(bufferSize, port);
    }

    UdpServer(int port) {
        init(0, port);
    }

    private void init(int bufferSize, int port) {
        mSocketBufferSize = bufferSize;
        try {
            mSocket = new DatagramSocket(port);
            if (mSocketBufferSize > 0) {
                mSocket.setReceiveBufferSize(mSocketBufferSize);
            }
            if (mSocket.isBound()) {
                mPort = mSocket.getLocalPort();
            }
            UdpTxData.getInstance().setUdpPort(mSocket);
            Log.d(TAG, "DatagramSocket init");
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        startTask();
    }

    public void stop() {
        try {
            isReadData = false;
            isSendData = false;
            unRegRxDataCallBack();
            if (mSocket != null) {
                mSocket.close();
                mSocket = null;
            }
        } catch (Exception e) {
            Logger.e("udp server stop Exception " + e.toString());
        }
    }

    public synchronized void startTask() {

        ThreadPoolManager.getInstance().createThreadPool();

        isReadData = true;
        ThreadPoolManager.getInstance().addTask(new UdpRxDataTask(mSocket));

        isSendData = true;
        ThreadPoolManager.getInstance().addTask(new UdpTxDataTask(UdpTxData.getInstance()));

    }

    public synchronized void sendPackage(byte[] parambytes, byte[] databytes) {
        UdpTxData.getInstance().sendPackage(parambytes, databytes);
    }

    public synchronized void regRxDataCallBack(@NonNull RxDataCallBack callBack) {
        UdpRxData.getInstance().setRxDataCallBack(callBack);
    }

    public synchronized void unRegRxDataCallBack() {
        UdpRxData.getInstance().setRxDataCallBack(null);
    }

}